<?php
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_init.php';
set_time_limit(0);
define('ORG_ID_TIMER', 'sihua');
//每次读取的数据条数
define('OP_DATA_NUM_EACH_TIME',80);
// class delete_media_c2_task extends nn_timer
// {

// 	public function action($params = null)
// 	{
// 		$this->msg('开始执行...');
// 		do_timer_action();
// 		$this->msg('执行结束...');
// 	}
// }
// $delete_media_c2_task = new delete_media_c2_task("delete_media_c2_task", ORG_ID_TIMER);
// $delete_media_c2_task->run();

// function do_timer_action()
// {
	include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_http_curl.class.php';
	include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/'.ORG_ID_TIMER.'/'.ORG_ID_TIMER.'_client.php';
	$data_file_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/log/op_queue/'.ORG_ID_TIMER.'/delete_media_task.txt';
	$dc = nl_get_dc(array (
			'db_policy' => NL_DB_WRITE
	));
	$dc->open();
	if (!file_exists($data_file_path))
	{
		//echo '数据文件不存在';
		return ;
	}
	// 逐行读取数据
	$data_file = fopen($data_file_path, 'r');
	$count = 0;
	$is_left_empty = true;
	$locked = flock($data_file, LOCK_EX + LOCK_NB);
	$data=array(
			'func'=>'check_is_exsist',
			'assets_video_type'=>'media',
	);
	$action = 'DELETE';
	$BizDomain = get_BizDomain();
	$sub_path = date('Y-m-d');
	$file_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/mgtv/' . ORG_ID_TIMER . '/inject_xml/' . $sub_path . '/';
	if (!is_dir($file_path))
	{
		mkdir($file_path, 0777, true);
	}
	$obj_curl = new np_http_curl_class();
	while (!feof($data_file))
	{
		if ($count <= OP_DATA_NUM_EACH_TIME)
		{
			$flag = false;
			$data_item = fgets($data_file);
			if (!$data_item)
			{
				$count ++;
				continue;
			}
			if ($count == OP_DATA_NUM_EACH_TIME)
			{
				// 最后一条时，记录剩余内容
				ob_start();
				fpassthru($data_file);
				$is_left_empty = false;
			}
			$data_item = make_utf8_string($data_item);
			$data_item = preg_replace("/\r\n/", '', rtrim($data_item));
			$data_item_arr = explode('{|--|}', $data_item);
			$sp_id = $data_item_arr[0];
			$data_id = $data_item_arr[1];
			$data_name = $data_item_arr[2];
			if(empty($data_id) || ($sp_id != ORG_ID_TIMER) || strlen($data_id) != 32)
			{
				$count++;
				continue;
            }
			$data['assets_id']=$data_id;
			$file_ret = $obj_curl->post(IMPROT_EPG_URL,$data);
			//判断CURL状态，如果不为200记录错误信息
			$curl_info = $obj_curl->curl_getinfo();
			@sleep(1);
            $http_code = $curl_info['http_code'];
			if($curl_info['http_code'] != '200')
			{
				exit;
			}
			//解析CURL返回结果
			$result_info = json_decode(json_encode(@simplexml_load_string($file_ret)),true);
			if(!empty($result_info['@attributes']['id']))
			{
				$count++;
				continue;
			}
			$sql="select count(*) as count from nns_vod_media where nns_id='{$data_id}'";
			$result = nl_query_by_db($sql, $dc->db());
			if(!$result || !is_array($result))
			{
				exit;
			}
			if($result[0]['count'] > 0)
			{
				$count++;
				continue;
			}
			$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
			$xml_str .= '<Objects>';
			$xml_str .= '<Object ElementType="Movie" ID="' .$data_id. '" Action="' . $action . '" Code="' .$data_id. '">';
			$xml_str .= '</Object>';
			$xml_str .= '</Objects>';
            $xml_str .= '</ADI>';
//             $data_id = stripslashes(trim($data_id));
//             if (substr($data_id, 0, 3) == "\xef\xbb\xbf") {
//                 $data_id = substr($data_id, 3);
//             }
			$file_name = 'movie_'.$data_id.'_'.$action.'.xml';
			$c2_id = np_guid_rand();
			$c2_info = array(
					'nns_id' => $c2_id,
					'nns_task_type'=>'Movie',
					'nns_task_id'=> np_guid_rand(),
					'nns_task_name'=> (isset($data_name) && !empty($data_name)) ? $data_name.'_temp' : '_temp',
					'nns_action'=>	$action,
					'nns_url' => $file_name,
					'nns_content' => $xml_str,
					'nns_desc' => 'Movie,'.$action,
                );
            //$c2_info['nns_url']=str_replace('%EF%BB%BF', '', $c2_info['nns_url']);
			file_put_contents($file_path.$c2_info['nns_url'], $xml_str);
			$c2_info['nns_url'] = $sub_path . '/' . $c2_info['nns_url'];
            $CmdFileURL = C2_FTP . $c2_info['nns_url'];
			try
			{
				$result = call_user_func_array(array (
						ORG_ID_TIMER . '_client', 
						'ExecCmd'
				), array (
						$c2_id, 
						$CmdFileURL
				));
				@sleep(1);
				$c2_info['nns_result'] = '[' . $result->Result . ']';
				save_c2_log($dc, $c2_info);
			} catch (Exception $e)
			{
				$c2_info['nns_result'] = '[-1]';
				$c2_info['nns_notify_result'] = -1;
				save_c2_log($dc, $c2_info);
			}
			$count++;
		}
		else
		{
			break;
		}
	}
	// 如果最后数据不为空，将剩余内容重新写入到文件中
	if ($is_left_empty)
	{
		$left_content = '';
	}
	else
	{
		$left_content = ob_get_clean();
	}
	flock($data_file, LOCK_EX + LOCK_NB);
	fclose($data_file);
	$result = file_put_contents($data_file_path, $left_content);
//}

function save_c2_log($dc,$c2_log){
	$c2_log['nns_type'] = 'std';
	$c2_log['nns_org_id'] = ORG_ID_TIMER;
	$dt = date('Y-m-d H:i:s');
	$c2_log['nns_create_time'] = $dt;
	$c2_log['nns_send_time'] = $dt;
	return nl_db_insert($dc->db(),'nns_mgtvbk_c2_log',$c2_log);
}


function get_BizDomain()
{
	if(ORG_ID_TIMER=='hndx' || ORG_ID_TIMER=='hnlt_zx' || ORG_ID_TIMER == 'hndx_hw')
	{
		return 520;
	}
	else
	{
		return 2;
	}
}

function make_utf8_string($string)
{
	$encode = mb_detect_encoding($string, array("ASCII","UTF-8","GB2312","GBK","BIG5","EUC-CN"));
	if ($encode == "UTF-8")
	{
		return $string;
	}
	else if($encode == "ASCII")
	{
		$string = iconv("ASCII","UTF-8",$string);
	}
	else if($encode == "GB2312")
	{
		$string = iconv("GB2312","UTF-8",$string);
	}
	else if($encode == "GBK")
	{
		$string = iconv("GBK","UTF-8",$string);
	}
	else if($encode == "BIG5")
	{
		$string = iconv("BIG5","UTF-8",$string);
	}
	else if($encode == "EUC-CN")
	{
		$string = iconv("EUC-CN","UTF-8",$string);
	}
	return $string;
}
